﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using POI.eTransmittal.BusinessRule;
using POI.eTransmittal.Enitity;
using System.IO;

namespace POI.eTransmittal.WebApp
{
    public partial class NewOutGoingTransmittal : BasePage
    {
        protected void Page_Init(object sender, EventArgs e)
        {
            RegisterXpodatasource(xpdsContact, xpodsDocType, xpodsUser,xpodsFax);
            CommonBusinessRules.PrepareDocTypeDefaultValues(CurrentUnitOfWork, CurrUserId);
        }
        const string KEY_CONTACT = "newOutGoingTransmittal_Contact";
        protected void Page_Load(object sender, EventArgs e)
        {
            StatusControl1.HideLoading();
            fillView();
         //   StatusControl1.
        }

        private void fillView()
        {
            string log = Request.QueryString["log"];
            if (!string.IsNullOrEmpty(log))
            {
                OutgoingTransmittal trns = CommonBusinessRules.GetOutgoingTransmittal(CurrentUnitOfWork, log);
                if (trns != null)
                {
                   
                    txtSubject.Text = trns.Subject;
                    cboAuthor.Text = trns.Author;
                    cboTo.Text = trns.To;
                    cboFax.Text = trns.FaxNo;
                    txtRemarks.Text = trns.Remarks;
                    cboDocType.Value = trns.DocTypeCode;
                    txtAttn.Text = trns.Attn;

                    lblCreatedBy.Text = trns.CreatedBy;
                    lblCreatedDate.Text = trns.CreatedDate.ToString("dd MMM yyy");
                    lblLog.Text = log+" ("+trns.Status+")";
                    btnChange.Enabled = true;
                    btnChange.Text = "Click here to upload";
                    if (!string.IsNullOrEmpty(trns.OriginalFileName))
                    {
                        btnChange.Text = trns.OriginalFileName;
                       // lblDoc.ClientVisible = true;
                        //linkFile.Text = trns.OriginalFileName;
                        //linkFile.NavigateUrl = trns.GetUNC_FileLink();
                        //linkFile.Target = "_blank";
                        //linkFile.ClientVisible = true;
                    }
                }
            }
            else
            {
               // upcDoc.Enabled = false;
                lblCreatedBy.Text = CurrUserId;
                lblCreatedDate.Text = DateTime.Now.ToString("dd MMM yyy");
                btnSubmit.Enabled = false;
                lblLog.Text = "(auto generated)";
                btnChange.Enabled = false;
                btnChange.Text = "Click here to upload";
            }
        }

        

        protected void btnSave_Click(object sender, EventArgs e)
        {
            save(false);
        }

        private void save(bool isSubmit)
        {
            string subject = txtSubject.Text;
            string author = cboAuthor.Text;
            string to = cboTo.Text;
            string attn = txtAttn.Text;
            string fax = cboFax.Text;
            string remarks = txtRemarks.Text;
            string doctype = cboDocType.Value == null ? "" : cboDocType.Value.ToString();

            string log = string.IsNullOrEmpty(Request.QueryString["log"]) ? "-1" : Request.QueryString["log"];
            try
            {

                if (string.IsNullOrEmpty(subject) || string.IsNullOrEmpty(author) || string.IsNullOrEmpty(to) || string.IsNullOrEmpty(attn) || string.IsNullOrEmpty(fax) || string.IsNullOrEmpty(doctype))
                {
                    throw new Exception("All entry is required, except remarks (optional)");
                }
                OutgoingTransmittal trns = CommonBusinessRules.GetOutgoingTransmittal(CurrentUnitOfWork, log);
                if (trns == null)
                {
                    trns = CommonBusinessRules.CreateNewOutGoingTransmittal(CurrentUnitOfWork, subject, author, to, attn, fax, remarks, doctype, CurrUserId);
                }
                else
                {
                    CommonBusinessRules.SaveOutgoing(CurrentUnitOfWork, log, subject, author, to, fax, doctype, attn, remarks, CurrUserId);
                }

                if (upcDoc.UploadedFiles.Length <= 0)
                {
                    if (isSubmit)

                        throw new Exception("Document is required for submitting.");
                }
                else
                {
                    if (upcDoc.UploadedFiles[0].FileName != "")
                    {
                        string ext = Path.GetExtension(upcDoc.UploadedFiles[0].FileName);

                        CommonBusinessRules.CheckExtention(CurrentUnitOfWork, ext);
                        trns.Reload();
                        log = trns.ID.ToString();
                        string path = CommonBusinessRules.GetOutgoingShareFolderToWrite(CurrentUnitOfWork, log);
                        //   step = 2;
                        string newFileName = CommonBusinessRules.GetOutgoingTransmittalFileName(CurrentUnitOfWork, log, Path.GetExtension(upcDoc.UploadedFiles[0].FileName));
                        string shareFolder = Path.Combine(path, newFileName);
                        upcDoc.UploadedFiles[0].SaveAs(shareFolder);
                        trns.FaxFileLink = shareFolder;
                        trns.OriginalFileName = upcDoc.UploadedFiles[0].FileName;
                        if(isSubmit)
                         trns.Status = OutgoingTransmittal.WAIT;
                        trns.Save();
                        CurrentUnitOfWork.CommitChanges();
                        if(isSubmit)
                        CommonBusinessRules.SubmitToCoordinator(trns, "http://" + HttpContext.Current.Request.Url.Host + "/" + HttpContext.Current.Request.ApplicationPath);
                    }
                }
                if(!isSubmit)
                SetStatusMessage("Your transmittal is succesfully saved.", trns.ID.ToString(), trns.RefNo);
                else
                    StatusControl1.SetStatusMessage("Your transmittal is succesfully submitted to coordinators.");
             
                //StatusControl1.SetNavigateUrl("NewOutgoingTransmittal.aspx?log=" + trns.ID.ToString());
                //   Response.Redirect("~/NewIncomingTransmittal.aspx?log=" + trns.ID.ToString());
                //  e.Result = string.Format("your transmittal no:{0} {1}your ref no:{2}", trns.ID, "<br/>", trns.RefNo);
            }
            catch (Exception ex)
            {
                StatusControl1.ShowErrorMessage(ex);
                //   throw new Exception("Error:Unable to create transmittal;" + ex.Message);
            }

        }
        public void SetStatusMessage(string message, string log, string refNo)
        {
            popInfo.ShowOnPageLoad = true;
            lblInfomessage.Text = message;
            lblUrl.Text = "NewOutgoingTransmittal.aspx?log=" + log;
            lblLogNo.Text = log;
            txtRefNo.Text  = refNo;
            txtRefNo.Focus();
            
        }
        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            save(true);
        }

        protected void cboFax_Callback(object sender, DevExpress.Web.ASPxClasses.CallbackEventArgsBase e)
        {
            int outTemp = -1;
            string[] strs=e.Parameter.Split(';');
            if (int.TryParse(strs[0], out outTemp))
            {
                Session[KEY_CONTACT] = strs[0];
                cboFax.DataBind();

            }
            else
            {
                cboFax.Text = strs[1];
            }
        }

        protected void clbCancel_Callback(object source, DevExpress.Web.ASPxCallback.CallbackEventArgs e)
        {
                string log = Request.QueryString["log"];
                if (!string.IsNullOrEmpty(log))
                {
                    OutgoingTransmittal trns = CommonBusinessRules.GetOutgoingTransmittal(CurrentUnitOfWork, log);
                    if (trns != null)
                    {
                        e.Result = trns.OriginalFileName;
                    }
                    else
                        e.Result = "Click here to upload";
                }
        }

    }
}